<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <el-select placeholder="选择用户" clearable v-model="queryInfo.userId" filterable default-first-option>
        <el-option v-for="user of userData" :label="user.userName" :value="user.id" :key="user.id"></el-option>
      </el-select>
      <el-select placeholder="选择商品" clearable v-model="queryInfo.goodsId" filterable default-first-option>
        <el-option v-for="goods of goodsData" :label="goods.goodsName" :value="goods.id" :key="goods.id"></el-option>
      </el-select>
      <el-input placeholder="请输入单价" clearable v-model="queryInfo.price"></el-input>
      <el-input placeholder="请输入数量" clearable v-model="queryInfo.num"></el-input>
      <el-input placeholder="请输入总价" clearable v-model="queryInfo.total"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      <!-- <el-upload action="http://localhost:7777/cart/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
        <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
      </el-upload>
      <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> -->
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55"></el-table-column>
      <el-table-column prop="userName" label="用户"></el-table-column>
      <el-table-column prop="goodsName" label="商品"></el-table-column>
      <el-table-column prop="price" label="单价"></el-table-column>
      <el-table-column prop="num" label="数量"></el-table-column>
      <el-table-column prop="total" label="总价"></el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="160"></el-table-column>
      <el-table-column label="操作"  width="180" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleEdit(scope.row.id)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button type="danger"  @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false" @close="handleDialogClose">
      <el-form label-width="140px" size="small" style="width: 85%;" :model="form" :rules="rules" ref="dialogForm">
        <el-form-item prop="userId" label="用户">
          <el-select placeholder="选择用户" clearable v-model="form.userId" filterable default-first-option>
            <el-option v-for="user of userData" :label="user.userName" :value="user.id" :key="user.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="goodsId" label="商品">
          <el-select placeholder="选择商品" clearable v-model="form.goodsId" filterable default-first-option>
            <el-option v-for="goods of goodsData" :label="goods.goodsName" :value="goods.id" :key="goods.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="单价">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="num" label="数量">
          <el-input v-model="form.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="total" label="总价">
          <el-input v-model="form.total" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cart",
  data() {
    return {
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 查询条件
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      // 表单数据
      form: {},
      // 对话框标题
      dialogTitle: "",
      // 对话框是否显示
      dialogFormVisible: false,
      // 批量选择
      multipleSelection: [],
      // 用户信息
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // 校验规则
      rules: {
        userId: [
          {required: true, message: '请输入用户', trigger: 'blur'}
        ],
        goodsId: [
          {required: true, message: '请输入商品', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入单价', trigger: 'blur'}
        ],
        num: [
          {required: true, message: '请输入数量', trigger: 'blur'}
        ],
        total: [
          {required: true, message: '请输入总价', trigger: 'blur'}
        ],
      },
      // 用户数据
      userData: [],
      // 商品数据
      goodsData: [],
    }
  },
  created() {
    this.load()
  },
  methods: {
    // 加载数据
    load() {
      // 加载购物车
      this.request.get("/cart/page", {
        params: this.queryInfo
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      // 加载用户
      this.request.get("/user").then(res => {
        this.userData = res.data
      })
      // 加载商品
      this.request.get("/goods").then(res => {
        this.goodsData = res.data
      })
    },
    // 添加
    handleAdd() {
      this.dialogTitle = "添加购物车"
      this.dialogFormVisible = true
    },
    // 修改
    async handleEdit(id) {
      const res = await this.request.get("/cart/" + id)
      this.form = res.data
      this.dialogTitle = "修改购物车"
      this.dialogFormVisible = true
    },
    // 保存
    save() {
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) {
          return
        }
        const res = await this.request.post("/cart", this.form)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success("保存成功")
        this.dialogFormVisible = false
        this.load()
      })
    },
    // 删除
    del(id) {
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          const res = await this.request.delete("/cart/" + id)
          if (res.code !== 200) {
            return this.$message.error("删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === 1 && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除
    delBatch() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          let ids = this.multipleSelection.map(item => item.id)
          const res = await this.request.delete("/cart/del/batch", {data: ids})
          if (res.code !== 200) {
            return this.$message.error("批量删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === ids.length && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 重置
    reset() {
      this.queryInfo = {
        pageNum: 1,
        pageSize: 5
      }
      this.load()
    },
    // 监听页大小改变
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.load()
    },
    // 监听页码改变
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.load()
    },
    // 文件上传成功的回调
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    // 图片上传成功的回调
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    // 下载
    download(url) {
      window.open(url)
    },
    // 导出
    exp() {
      window.open("http://localhost:7777/cart/export")
    },
    // 导入
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    // 对话框关闭
    handleDialogClose() {
      this.dialogFormVisible = false
      this.form = {}
      this.$refs.dialogForm.resetFields() // 重置表单
      if (this.$refs.img) {
        this.$refs.img.clearFiles();
      }
      if (this.$refs.file) {
        this.$refs.file.clearFiles();
      }
    },
  }
}
</script>

<style scoped style="less">
.search{
  margin: 10px 0;

  .el-input {
    width: 150px;
    margin-right: 10px;
  }
  .el-select {
    width: 140px;
    margin-right: 10px;
  }
}

.headerBg {
  background: #eee!important;
}
</style>